package core;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 公共的servlet
 */
public abstract class BaseServlet extends HttpServlet {


    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取传递的方法
        String m = request.getParameter("m");
        if (m == null || m.isEmpty()) {
            throw new ServletException("方法名字必传!");
        }
        try {
            // 获取class 对象
            // this  实际运行的servlet的对象
            Class<? extends BaseServlet> clazz = this.getClass();
            // 获取方法对象
            Method method = clazz.getDeclaredMethod(m, HttpServletRequest.class, HttpServletResponse.class);
            // 动态调用
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            throw new ServletException("该方法不存在!!");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }
}
